﻿using System.Linq;
using log4net;

namespace Reactor.Environment
{
    public class BrokerConnectionDetails
    {
        #region Fields

        private const string UriPrefix = "uri=";
        private const string UserPrefix = "user=";
        private const string PwPrefix = "pw=";
        private static readonly ILog Log = LogManager.GetLogger(typeof (BrokerConnectionDetails));

        #endregion

        /// <summary>
        /// Initializes a new instance of the <see cref="BrokerConnectionDetails"/> class. Will use the supplied raw connection string 
        /// to initialize this instance.
        /// </summary>
        /// <param name="rawConnectionString">The raw connection string.</param>
        public BrokerConnectionDetails(string rawConnectionString)
        {
            LoadConnectionString(rawConnectionString);
        }

        /// <summary>
        /// Gets or sets the URI.
        /// </summary>
        /// <value>The URI.</value>
        public string Uri { get; set; }

        /// <summary>
        /// Gets or sets the user.
        /// </summary>
        /// <value>The user.</value>
        public string User { get; set; }

        /// <summary>
        /// Gets or sets the password.
        /// </summary>
        /// <value>The password.</value>
        public string Password { get; set; }

        private void LoadConnectionString(string connectionString)
        {
            if (string.IsNullOrEmpty(connectionString))
            {
                if (Log.IsDebugEnabled) Log.Debug("BrokerConnectionString AppSetting not found.");
                return;
            }

            var pieces = connectionString.Split(';');
            if (pieces.Length == 0)
            {
                if (Log.IsDebugEnabled) Log.Debug("BrokerConnectionString AppSetting empty.");
                return;
            }

            if (!connectionString.ToLower().Contains(UriPrefix))
            {
                if (Log.IsDebugEnabled) Log.Debug("BrokerConnectionString AppSetting missing uri.");
                return;
            }

            Uri = pieces.Where(p => p.Contains(UriPrefix)).SingleOrDefault().Replace(UriPrefix, string.Empty);
            User = pieces.Where(p => p.Contains(UserPrefix)).SingleOrDefault().Replace(UserPrefix, string.Empty);
            Password = pieces.Where(p => p.Contains(PwPrefix)).SingleOrDefault().Replace(PwPrefix, string.Empty);
        }

        public override string ToString()
        {
            return string.Format("uri={0};user={1};pw={2};", Uri, User, Password);
        }
    }
}
